/*
 * @Author: wwssaabb
 * @Date: 2021-07-08 09:58:39
 * @LastEditTime: 2021-07-14 15:30:55
 * @FilePath: \demo\blog_demo\route\admin.js
 */

//博客后台管理路由
const path=require('path')
const router=require('koa-router')()
const {run,check}=require(path.join(__dirname,'../hash.js'))

const {setUser,getUser}=require('./user')

//当前路由加前缀
router.prefix('/admin')

const {User}=require(path.join(__dirname,'../model/user'))

//get请求

//登录页面
router.get('/login',async (ctx,next)=>{
  ctx.render('admin/login')
})

//用户管理页面
router.get('/user',async (ctx,next)=>{
  const _user=getUser()
  
  let {page,size}=ctx.request.query
  page=parseInt(page?page:1)
  size=parseInt(size?size:20)
  let totalCount=await User.countDocuments()
  let totalPage=Math.ceil(totalCount/size)
  let pages=[]
  for(i=0;i<totalPage;i++){
    pages.push(`/admin/user?page=${i+1}&size=${size}`)
  }
  let list=await User.find({},{password:0}).skip((page-1)*size).limit(size)

  //console.log({list,totalCount,totalPage,pages})
  ctx.render('admin/user',{userInfo:_user,list,totalCount,totalPage,pages,currentPage:page,size,active:'user'})
})

//用户管理编辑页面
router.get('/user-edit',async (ctx,next)=>{
  const _user=getUser()
  const {_id}=ctx.request.query
  let info=null
  if(_id){
    info=await User.findOne({_id},{__v:0})
    info.password
  }
  ctx.render('admin/user-edit',{userInfo:_user,info})
})

//用户文章页面
router.get('/article',async (ctx,next)=>{
  const _user=getUser()
  let {page,size}=ctx.request.query
  page=parseInt(page?page:1)
  size=parseInt(size?size:20)
  let totalCount=await Article.countDocuments()
  let totalPage=Math.ceil(totalCount/size)
  let pages=[]
  for(i=0;i<totalPage;i++){
    pages.push(`/admin/article?page=${i+1}&size=${size}`)
  }
  let list=await Article.find({},{__v:0}).skip((page-1)*size).limit(size).populate('author').lean()

  ctx.render('admin/article',{userInfo:_user,active:'article',list,totalCount,totalPage,pages,currentPage:page,size})
})

//用户文章管理页面
router.get('/article-edit',async (ctx,next)=>{
  const _user=getUser()
  const  {_id}=ctx.request.query
  const articleInfo=await Article.findOne({_id},{__v:0})

  console.log(articleInfo)
  ctx.render('admin/article-edit',{userInfo:_user,articleInfo})
})

//退出登录
router.get('/logout',async (ctx,next)=>{
  ctx.session.username=null
  setUser(null)
  ctx.redirect('/admin/login')
})

//post请求

//登录功能

router.post('/login',async (ctx,next)=>{  
  const {email,password}=ctx.request.body
  //效验登录数据
  if(email.trim().length==0||password.trim().length==0){
    ctx.status=400
    ctx.render('admin/error',{msg:'邮件地址或密码错误'})
    return
  }
  let user=await User.findOne({email})
  if(user){                                 
    let isPass= await check(password,user.password)
    if(isPass){
      ctx.status=301
      //设置session、cookie
      ctx.session.username=user.username
      //设置模板引擎的全局数据
      setUser(user)
      //登录成功，重定向到user路由
      //ctx.render('admin/user')
      if(user.role=='admin'){
        ctx.redirect('/admin/user')
      }else{
        ctx.redirect('/blog/')
      }
    }else{
      ctx.status=400
      ctx.render('admin/error',{msg:'邮件地址或密码错误'})
    }
  }else{
    ctx.status=400
    ctx.render('admin/error',{msg:'邮件地址或密码错误'})
  }
  
  await next()
})

//新增用户功能
const joi_check=require('../joi')
router.post('/user-edit',async (ctx,next)=>{  
  const {username,email,password,role,state}=ctx.request.body
  
  //利用joi模块效验登录数据
  const res=await joi_check(ctx.request.body)

  if(typeof res ==='string'){ //res为string时为错误信息

    ctx.status=400
    ctx.render('admin/user-edit',{msg:res})

  }else{  //res为对象时通过验证返回的对象

    //检查邮箱是否注册
    let isRegister=await User.findOne({email})
    if(isRegister){
      ctx.status=400
      ctx.render('admin/user-edit',{msg:'该邮箱已被注册！'})
      return
    }
    
    //创建用户
    let user=await createUser(ctx.request.body)
    //ctx.render('admin/user')
    ctx.redirect('/admin/user')
  }
  
})

//修改用户功能
router.post('/user-modify',async (ctx)=>{
  const _user=ctx.request.body
  let {_id} =ctx.request.query
  let user=await editUSer(_id,_user)
  if(user){
    ctx.redirect('/admin/user')
  }else{
    ctx.render('admin/user',{info:_user,msg:'修改失败'})
  }
  
})

//删除用户功能
router.post('/user-delete',async (ctx)=>{
  const {page,size} =ctx.request.query
  const {_id}=ctx.request.body
  let res=await deleteUser(_id)
  if(res['ok']){
    ctx.redirect('/admin/user?page='+page+'&size='+size)
  }else{
    ctx.render('admin/error',{msg:'删除失败'})
  }
})

//添加文章
const formidable  = require("formidable")
const Article = require('../model/article')
router.post('/article-add',async (ctx)=>{
  const form=formidable({
    multiples:true,
    uploadDir:path.join(__dirname,'../public/uploads'),
    keepExtensions:true
  })
  await form.parse(ctx.req,async (err,fields,files)=>{
    if(err){
      console.log(err)
    }else{
      const {title,author,publishDate,content} = fields
      let {cover} =files
      let obj={
        title,
        author,
        cover:'\\'+cover.path.match(/uploads.+/g)[0],
        content
      }
      if(publishDate){
        obj.publishDate=publishDate
      }
      await Article.create(obj)
    }
  })
  ctx.status=302
  ctx.redirect('/admin/article')
})
//方法

//修改用户
async function editUSer(_id,obj){
  let user
  let {username,email,password,role,state}=obj
  let old=await User.findOne({_id})
  let isEqual=await check(password,old.password)
  let newPassword_hash=password
  if(old.password===password||isEqual){
    user=await User.updateOne({_id},{
      username,
      email,
      role,
      state
    })
  }else{
    newPassword_hash=await run(password)
    user=await User.updateOne({_id},{
      username,
      email,
      password:newPassword_hash,
      role,
      state
    })
  }
  return user
}

//创建用户
async function createUser(obj){
  let {username,email,password,role,state}=obj
  const password_hash=await run(password)
  const user=await User.create({
    username,
    email,
    password:password_hash,
    role,
    state
  })
  return user
}

//删除用户
async function deleteUser(_id){
  let res=await User.deleteOne({_id})
  console.log(res)
  return res
}

module.exports=router